<?php

namespace app\api\controller;

use think\Config;
use think\Controller;
use think\Request;
use app\common\controller\Api;

use FFMpeg\FFMpeg;
use FFMpeg\FFProbe;



class Song extends Api
{

//    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $model;



    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('app\common\model\Song');

    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $category_id = $this->request->request('category_id','');
        $name = $this->request->request('name','');
        $model = $this->model->field('id,name,singer');
        if ($category_id) $model = $model->where('category_id',$category_id);
        if ($category_id) $model = $model->whereLike('name','%'.$name.'%');
        $list = $model->where('switch',1)->paginate();
        $this->success('success',$list);
        //
    }


    public function category(){
        $list = model('app\common\model\Category')
            ->field('id,name,image,type,flag')
            ->where('status','normal')
            ->where('type','default')
            ->order('weigh','desc')->paginate();
        foreach ($list as $k=>$v){
            $list[$k]['count'] = $this->model->where('category_id',$v['id'])->where('switch',1)->count();

        }

        $this->success('success',$list);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {

    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $row = $this->model->where('id',$id)->find();
        $user = $this->auth->getUserinfo();
        $row['play_all'] = 0;
        if ($user['level'] >0){
            $row['play_all'] = 1;
        }else{
            if (model('app\common\model\buy\Song')
                ->where('song_id',$id)
                ->where('user_id',$this->auth->id)->find()){
                $row['play_all'] = 1;
            }

            if (model('app\common\model\buy\Song')
                ->where('song_id',$id)
                ->where('recommend',$this->auth->id)->find()){
                $row['play_all'] = 1;
            }
        }

        $row['collect'] = model('app\common\model\Collect')
            ->where('song_id',$id)
            ->where('user_id',$this->auth->id)
            ->where('state','collect')
            ->count();



        $learnarr = json_decode($row['learnjson'],true);
        $learnitemsjsonarr = json_decode($row['learnitemsjson'],true);


        $aijsonarr = json_decode($row['aijson'],true);
        $aiitemsjsonarr = json_decode($row['aiitemsjson'],true);

        $row['learnarr'] = [];
        $row['aiarr'] = [];
        
        
      
        
        // $learn_paht = ROOT_PATH.'public'.$row['learn_file'];
   
        // $row['learn_resolution'] = $this->getVideoResolution($learn_paht);
        
        // $video = ROOT_PATH.'public'.$row['video'];
        
        // $row['video_resolution'] = $this->getVideoResolution($video);
        
        // $ai = ROOT_PATH.'public'.$row['ai_file'];
        
        // $row['ai_resolution'] = $this->getVideoResolution($ai);
        
        
        // $back = ROOT_PATH.'public'.$row['back_file'];
        
        // $row['back_resolution'] = $this->getVideoResolution($back);
        
        
        // $song = ROOT_PATH.'public'.$row['song_file'];
        
        // $row['song_resolution'] = $this->getVideoResolution($song);
        
        // dump($video);exit();
        
        
        // print_r("<pre>");print_r($FFMpeg);exit();

        if ($learnarr){


            foreach ($learnarr as $k=>$v){
                $learnarr[$k]['learna_part'] = model('app\common\model\sys\Part')->where('id',$v['id'])->value('name');
                $learnitems = [];
                foreach ($learnitemsjsonarr as $ks=>$vs){
                    $i = 0;
                        if ($v['id'] == $vs['id']){
                            $i = count($learnitems);
                            $items = [
                                'items_text'=> $this->setNumber($i).'句',
                                'items_count'=>$i+1,
                            ];
                            $learnitems[] = array_merge($items,$vs);
                        }
                }

                $learnarr[$k]['learna_des'] = $learnitems;



            }

            unset($row['learnjson']);
            unset($row['learnitemsjson']);
        }


        if ($aijsonarr){
            foreach ($aijsonarr as $kz=>$vz){
                $aijsonarr[$kz]['ai_part'] = model('app\common\model\sys\Part')->where('id',$vz['id'])->value('name');
                $aiitems = [];
//                var_dump($vz['id']);
                foreach ($aiitemsjsonarr as $ksz=>$vsz){
//                    $i = 0;
//                    var_dump($vz['id'].'-'.$vsz['id']);
                    if ($vz['id'] == $vsz['id']){
                        $i = count($aiitems);
                        $items = [
                            'items_text'=> $this->setNumber($i).'句',
                            'items_count'=>$i+1,
                        ];

                        $aiitems[] = array_merge($items,$vsz);
//                        print_r($aiitems);print_r($aiitems);
                    }
                }

                $aijsonarr[$kz]['ai_des'] = $aiitems;

            }
            unset($row['aijson']);
            unset($row['aiitemsjson']);
        }
//        print_r("<pre>");print_r($aijsonarr);exit();
        $row['learnarr'] = $learnarr;
        $row['aiarr'] = $aijsonarr;

        $reqs = model('app\common\model\Collect')
            ->where('song_id',$id)
            ->where('user_id',$this->auth->id)
            ->where('state','browse')
            ->find();
        if ($reqs){
            $reqs->createtime = time();
            $reqs->save();
        }else{
            model('app\common\model\Collect')->insert(['user_id'=>$this->auth->id,
            'song_id'=>$id,'createtime'=>time(),'state'=>'browse'
            ]);
    }



//        print_r("<pre>");print_r($learnarr);
//        print_r("<pre>");print_r($learnitemsjsonarr);

        $this->success('success',$row);
    }
    
    
    
function getVideoResolution($videoPath) {
    if (!file_exists($videoPath)) {
        return '文件不存在';
    }
 
    // 构建FFmpeg命令
    $command = "ffprobe -v quiet -print_format json -show_format -show_streams $videoPath";
 

    // 执行命令并获取输出
    exec($command, $output, $returnVar);
    
      $width = trim($output[11]);
      $height = trim($output[12]);
      
      
      preg_match_all('/\d+/', $width, $matches);
      $width = $matches[0];
      
      preg_match_all('/\d+/', $height, $matchesz);
      $height = $matchesz[0];
    
    $data['height'] = $height[0];
    $data['width'] = $width[0];
    
 
    return $data;
}
    
    
        // function getContent($file)
//     {
//         /////$file为视频上传目录 
//         $command = sprintf('/usr/bin/', $file);//你的安装路径
//         ob_start();
//         passthru($command);
//         $info = ob_get_contents();
//         ob_end_clean();
//         // var_dump($command);exit();
//         $data = array();
//         if (preg_match("/Duration: (.*?), start: (.*?), bitrate: (\d*) kb\/s/", $info, $match)) {
//             $arr_duration = explode(':', $match[1]);
//             $data['seconds'] = $arr_duration[0] * 3600 + $arr_duration[1] * 60 + $arr_duration[2]; //转换播放时间为秒数
//             $data['start'] = $match[2]; //开始时间
//             $data['bitrate'] = $match[3]; //码率(kb)
//         }
//         if (preg_match("/Video: (.*?), (.*?), (.*?)[,\s]/", $info, $match)) {

//             $data['vcodec'] = $match[1]; //视频编码格式
//             $data['vformat'] = $match[2]; //视频格式
//             $data['resolution'] = $match[3]; //视频分辨率
//             $arr_resolution = explode('x', $match[3]);
//             $data['width'] = $arr_resolution[0];
//             var_dump( $data['width']);
// //            $data['height'] = $arr_resolution[1];
//         }
//         if (preg_match("/Audio: (\w*), (\d*) Hz/", $info, $match)) {
//             $data['acodec'] = $match[1]; //音频编码
//             $data['asamplerate'] = $match[2]; //音频采样频率
//         }
//         if (isset($data['seconds']) && isset($data['start'])) {
//             $data['play_time'] = $data['seconds'] + $data['start']; //实际播放时间
//         }
//         $data['size'] = filesize($file); //文件大小
        
//         return $data;
//         return json($data);
//     }




    public function setNumber($number)
    {
        $array = ['一','二','三','四','五','六','七','八','九','十',
        '十一','十二','十三','十四','十五',
        '十六','十七','十八','十九','二十',
        ];
        return $array[$number];
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }


    public function collect($id)
    {
        if ($id){
            $row = model('app\common\model\Collect')->where('song_id',$id)
                ->where('user_id',$this->auth->id)
                ->where('state','collect')
                ->find();
            if ($row) $row->delete();
            else  model('app\common\model\Collect')->insert(['user_id'=>$this->auth->id,
                'song_id'=>$id
                ]);
        }
        $this->success('操作成功');


    }
}
